package com.easy.work.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.syslib.impl.OnSelectCityImpl;
import com.base.syslib.impl.OnSelectProCityImpl;
import com.base.syslib.util.FileUtils;
import com.base.syslib.util.MessageTools;
import com.base.syslib.view.wheelview.BaseWheelView;
import com.base.syslib.view.wheelview.OnWheelChangedListener;
import com.base.syslib.view.wheelview.city.ArrayWheelAdapter;
import com.base.syslib.view.wheelview.city.CityWheelView;
import com.base.syslib.view.wheelview.city.model.CityModel;
import com.base.syslib.view.wheelview.city.model.DistrictModel;
import com.base.syslib.view.wheelview.city.model.ProvinceModel;
import com.easy.work.R;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Admin on 2018/1/24.
 */

public class ProCityDialog implements OnWheelChangedListener {

    private CityWheelView mViewProvince;
    private CityWheelView mViewCity;

    private Dialog dialog;
    private LinearLayout txt_msg;

    private LinearLayout lLayout_bg;
    private TextView txt_title;
    private Context context;
    private Button btn_neg;
    private Button btn_pos;
    private ImageView img_line;
    int screenWidth = 0;
    int screenHeight = 0;
    private LayoutInflater inflater = null;

    private int mYear = 2015;
    private int mMonth = 0;
    private int mDay = 1;

    View view = null;
    private String initDate;


    /**
     *
     */
    public ProCityDialog(Context context) {
        this.context = context;
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
    }

    public ProCityDialog builder() {
        // 获取Dialog布局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_date, null);
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        txt_msg = (LinearLayout) view.findViewById(R.id.txt_msg);
        txt_msg.addView(getUpViews());

        // 获取自定义Dialog布局中的控件
        lLayout_bg = (LinearLayout) view.findViewById(R.id.lLayout_bg);
        txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setText("请选择省市");
        txt_msg = (LinearLayout) view.findViewById(R.id.txt_msg);
        btn_neg = (Button) view.findViewById(R.id.btn_neg);
        btn_pos = (Button) view.findViewById(R.id.btn_pos);
        img_line = (ImageView) view.findViewById(R.id.img_line);

        // 定义Dialog布局和参数
        dialog = new Dialog(context, R.style.AlertDialogStyle);
        // dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.setContentView(view);

        // 调整dialog背景大小
        lLayout_bg.setLayoutParams(new FrameLayout.LayoutParams(screenWidth, LinearLayout.LayoutParams.WRAP_CONTENT));
        setUpData();
        return this;
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(context, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    private View getUpViews() {
        view = inflater.inflate(R.layout.wheel_pro_city_picker, null);
        mViewProvince = (CityWheelView) view.findViewById(R.id.province);
        mViewCity = (CityWheelView) view.findViewById(R.id.city);
        setUpListener();
        return view;
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        ProvinceModel provinceModel = provinceList.get(mViewProvince.getCurrentItem());
        String[] cities = mCitisDatasMap.get(provinceModel.getCode());
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }


    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {

        ProvinceModel provinceModel = provinceList.get(mViewProvince.getCurrentItem());
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(provinceModel.getCode())[pCurrent];
        String cityCode = provinceModel.getRegionEntityList().get(mViewCity.getCurrentItem()).getCode();
        String[] areas = mDistrictDatasMap.get(cityCode);

        if (areas == null) {
            areas = new String[]{""};
        }

    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
    }

    public ProCityDialog setPositiveButton(String text, final OnSelectProCityImpl onSelectCity) {
        if (TextUtils.isEmpty(text)) {
            btn_pos.setText("确定");
        } else {
            btn_pos.setText(text);
        }
        btn_pos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ProvinceModel provinceModel = provinceList.get(mViewProvince.getCurrentItem());
                String cityCode = provinceModel.getRegionEntityList().get(mViewCity.getCurrentItem()).getCode();
                String cityName = mCurrentCityName;
//                if (mCurrentCityName.equals("直辖市")) {
//                    cityName = mCurrentProviceName;
//                }
                if (provinceModel.getRegionEntityList().size() == 1) {
                    cityName = mCurrentProviceName;
                }
                if (mCurrentCityName.equals("市辖区")) {
                    cityName = mCurrentProviceName;
                }
                if (mCurrentCityName.equals("县")) {
                    cityName = mCurrentProviceName;
                }
                onSelectCity.selectCity(cityName, cityCode);
            }
        });
        return this;
    }

    public void show() {
        dialog.show();
    }

    public ProCityDialog setNegativeButton(String text) {
        if (TextUtils.isEmpty(text)) {
            btn_neg.setText("取消");
        } else {
            btn_neg.setText(text);
        }
        btn_neg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        return this;
    }

    List<ProvinceModel> provinceList = new ArrayList<>();

    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;


    /**
     * 解析省市区的XML数据
     */

    protected void initProvinceDatas() {

        AssetManager asset = context.getAssets();
        try {
            InputStream input = asset.open("city_info.txt");
            String message = FileUtils.inputStreamToStr(input);
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray Jarray = parser.parse(message).getAsJsonArray();

            // 获取解析出来的数据
            for (JsonElement obj : Jarray) {
                ProvinceModel provinceModel = gson.fromJson(obj, ProvinceModel.class);
                provinceList.add(provinceModel);
            }


            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getRegion();
                List<CityModel> cityList = provinceList.get(0).getRegionEntityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getRegion();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getRegion();
                List<CityModel> cityList = provinceList.get(i).getRegionEntityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getRegion();
                    List<DistrictModel> districtList = cityList.get(j).getRegionEntityList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getRegion(), districtList.get(k).getCode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
//                        String districtCode = provinceList.get(i).getRegionEntityList().get(j).getRegionEntityList().get(k).getCode();
                        mZipcodeDatasMap.put(districtList.get(k).getCode(), districtList.get(k).getCode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getRegion();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityList.get(j).getCode(), distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getCode(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }

    @Override
    public void onChanged(BaseWheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        }
    }


    private void showSelectedResult() {
        MessageTools.showToast(context, "当前选中:" + mCurrentProviceName + "," + mCurrentCityName);
    }
}
